package com.imarban.spring.controller.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.imarban.spring.business.user.UserBs;
import com.imarban.spring.model.User;

@Controller
@RequestMapping("/user/gestionar-user")
public class GestionarUser {

	@Autowired
	private UserBs userBs;

	@RequestMapping(value = "/new", method = RequestMethod.GET)
	public ModelAndView editNew() {
		return new ModelAndView("user/editNew", "new-user", new User());
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(
			Model m,
			@Validated(value = MinimalUserValidation.class) @ModelAttribute("new-user") User user,
			BindingResult result) {

		if (result.hasErrors()) {
			return "user/editNew";
		} else {

			Integer id = userBs.guardar(user);
			m.addAttribute("message", "Agregué al usuario " + user.getName() + " con el id: " + id);

			return "user/salida";
		}
	}
}